#!/usr/bin/env python
# -*- coding: utf-8 -*-

from subprocess import Popen, PIPE
import json
import os
import sys
import time
from multiprocessing import cpu_count

core_total = cpu_count()

def create_record(metric, value):
    metric_dict={"load1minPerCPU":"load.1minPerCPU","load5minPerCPU":"load.5minPerCPU","load15minPerCPU":"load.15minPerCPU"}
    record = {}
    record['Metric']      = metric_dict.get(metric)
    record['Endpoint']    = os.uname()[1]
    record['Timestamp']   = int(time.time())
    record['Step']        = 60
    record['Value']       = value
    record['CounterType'] = 'GAUGE'
    record['TAGS']        = ''
    return record

def get_cpu_load():
    load_data={}
    load_object=open('/proc/loadavg','r')
    allavg=load_object.readline()
    load1minPerCPU=float(allavg.split()[0])/core_total
    load5minPerCPU=float(allavg.split()[1])/core_total
    load15minPerCPU=float(allavg.split()[2])/core_total
    load_object.close()
    load_data['load1minPerCPU'] = load1minPerCPU
    load_data['load5minPerCPU'] = load5minPerCPU
    load_data['load15minPerCPU'] = load15minPerCPU
    return load_data

if __name__ == '__main__':
    load_data = get_cpu_load()
    data=[]
    for metric in load_data.keys():
        value = load_data.get(metric)
        data.append(create_record(metric,value))
    print json.dumps(data)
